package com.gls.starter.data.jpa.repository.impl;

import com.gls.starter.data.jpa.repository.BaseRepository;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.List;

/**
 * @param <Entity>
 * @param <ID>
 * @author lizhiyong
 */
public class BaseRepositoryImpl<Entity, ID extends Serializable> extends SimpleJpaRepository<Entity, ID>
        implements BaseRepository<Entity, ID> {

    // private final EntityManager entityManager;

    // private final JpaEntityInformation<Entity, ID> entityInformation;

    public BaseRepositoryImpl(JpaEntityInformation<Entity, ID> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        // this.entityInformation = entityInformation;
        // this.entityManager = entityManager;
    }

    @Override
    public long count(Entity entity) {
        return count(getExample(entity));
    }

    @Override
    public List<Entity> findAll(Entity entity) {
        return findAll(getExample(entity));
    }

    @Override
    public Page<Entity> findAll(Entity entity, Pageable pageable) {
        return findAll(getExample(entity), pageable);
    }

    @Override
    public List<Entity> findAll(Entity entity, Sort sort) {
        return findAll(getExample(entity), sort);
    }

    @Override
    public Entity findOne(Entity entity) {
        return findOne(getExample(entity)).get();
    }

    private Example<Entity> getExample(Entity entity) {
        Example<Entity> example = Example.of(entity);
        return example;
    }

}
